package cn.levi.path.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.levi.path.annotation.FilePathAuto;
import cn.levi.path.component.URLPathHandler;
import cn.levi.path.configuration.UrlProperties;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import java.io.IOException;
import java.util.Objects;

/**
 * 文件路径自定义序列化
 */
public class FilePathSerializer extends JsonSerializer<String> implements ContextualSerializer {

	private FilePathAuto filePathAuto;

	public FilePathSerializer(){}

	public FilePathSerializer(FilePathAuto filePathAuto) {
		this.filePathAuto = filePathAuto;
	}

	@Override
	public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
		UrlProperties urlProperties = SpringUtil.getBean(UrlProperties.class);
		if (!urlProperties.isEnable()) {
			gen.writeString(value);
			return;
		}
		if (StrUtil.isBlank(value)) {
			gen.writeString(value);
			return;
		}
		String host = filePathAuto.host();
		URLPathHandler urlPathHandler = SpringUtil.getBean(URLPathHandler.class);
		gen.writeString(StrUtil.isBlank(host) ? urlPathHandler.concatUrlPrefix(value) : StrUtil.addPrefixIfNot(value, host));
	}

	@Override
	public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
		if (property ==null){
			return prov.findNullValueSerializer(null);
		}
		if (!Objects.equals(property.getType().getRawClass(), String.class)) {
			return prov.findValueSerializer(property.getType(), property);
		}
		FilePathAuto filePathAutoTarget = property.getAnnotation(FilePathAuto.class);
		if (filePathAutoTarget == null) {
			return prov.findValueSerializer(property.getType(), property);
		}
		return new FilePathSerializer(filePathAutoTarget);
	}
}
